<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="优惠券名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入优惠券名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="兑换的优惠券面值" prop="money">
            <el-input v-model="queryParams.money" placeholder="请输入兑换的优惠券面值" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="是否限量, 默认0 不限量， 1限量" prop="isLimited">
            <el-input v-model="queryParams.isLimited" placeholder="请输入是否限量, 默认0 不限量， 1限量" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="发放总数" prop="total">
            <el-input v-model="queryParams.total" placeholder="请输入发放总数" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="剩余数量" prop="lastTotal">
            <el-input v-model="queryParams.lastTotal" placeholder="请输入剩余数量" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="所属商品id / 分类id" prop="primaryKey">
            <el-input v-model="queryParams.primaryKey" placeholder="请输入所属商品id / 分类id" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="最低消费，0代表不限制" prop="minPrice">
            <el-input v-model="queryParams.minPrice" placeholder="请输入最低消费，0代表不限制" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="可领取开始时间" prop="receiveStartTime">
            <el-date-picker clearable
              v-model="queryParams.receiveStartTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择可领取开始时间"
            />
          </el-form-item>
          <el-form-item label="可领取结束时间" prop="receiveEndTime">
            <el-date-picker clearable
              v-model="queryParams.receiveEndTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择可领取结束时间"
            />
          </el-form-item>
          <el-form-item label="是否固定使用时间, 默认0 否， 1是" prop="isFixedTime">
            <el-input v-model="queryParams.isFixedTime" placeholder="请输入是否固定使用时间, 默认0 否， 1是" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="可使用时间范围 开始时间" prop="useStartTime">
            <el-date-picker clearable
              v-model="queryParams.useStartTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择可使用时间范围 开始时间"
            />
          </el-form-item>
          <el-form-item label="可使用时间范围 结束时间" prop="useEndTime">
            <el-date-picker clearable
              v-model="queryParams.useEndTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择可使用时间范围 结束时间"
            />
          </el-form-item>
          <el-form-item label="天数" prop="day">
            <el-input v-model="queryParams.day" placeholder="请输入天数" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model="queryParams.sort" placeholder="请输入排序" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['crm:storeCoupon:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['crm:storeCoupon:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['crm:storeCoupon:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['crm:storeCoupon:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="storeCouponList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="优惠券表ID" align="center" prop="id" v-if="false" />
        <el-table-column label="优惠券名称" align="center" prop="name" />
        <el-table-column label="兑换的优惠券面值" align="center" prop="money" />
        <el-table-column label="是否限量, 默认0 不限量， 1限量" align="center" prop="isLimited" />
        <el-table-column label="发放总数" align="center" prop="total" />
        <el-table-column label="剩余数量" align="center" prop="lastTotal" />
        <el-table-column label="使用类型 1 全场通用, 2 商品券, 3 品类券" align="center" prop="useType" />
        <el-table-column label="所属商品id / 分类id" align="center" prop="primaryKey" />
        <el-table-column label="最低消费，0代表不限制" align="center" prop="minPrice" />
        <el-table-column label="可领取开始时间" align="center" prop="receiveStartTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.receiveStartTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="可领取结束时间" align="center" prop="receiveEndTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.receiveEndTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否固定使用时间, 默认0 否， 1是" align="center" prop="isFixedTime" />
        <el-table-column label="可使用时间范围 开始时间" align="center" prop="useStartTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.useStartTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="可使用时间范围 结束时间" align="center" prop="useEndTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.useEndTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="天数" align="center" prop="day" />
        <el-table-column label="优惠券类型 1 手动领取, 2 新人券, 3 赠送券" align="center" prop="type" />
        <el-table-column label="排序" align="center" prop="sort" />
        <el-table-column label="状态" align="center" prop="status" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['crm:storeCoupon:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['crm:storeCoupon:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改优惠券对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="storeCouponFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="兑换的优惠券面值" prop="money">
          <el-input v-model="form.money" placeholder="请输入兑换的优惠券面值" />
        </el-form-item>
        <el-form-item label="是否限量, 默认0 不限量， 1限量" prop="isLimited">
          <el-input v-model="form.isLimited" placeholder="请输入是否限量, 默认0 不限量， 1限量" />
        </el-form-item>
        <el-form-item label="发放总数" prop="total">
          <el-input v-model="form.total" placeholder="请输入发放总数" />
        </el-form-item>
        <el-form-item label="剩余数量" prop="lastTotal">
          <el-input v-model="form.lastTotal" placeholder="请输入剩余数量" />
        </el-form-item>
        <el-form-item label="所属商品id / 分类id" prop="primaryKey">
          <el-input v-model="form.primaryKey" placeholder="请输入所属商品id / 分类id" />
        </el-form-item>
        <el-form-item label="最低消费，0代表不限制" prop="minPrice">
          <el-input v-model="form.minPrice" placeholder="请输入最低消费，0代表不限制" />
        </el-form-item>
        <el-form-item label="可领取开始时间" prop="receiveStartTime">
          <el-date-picker clearable
            v-model="form.receiveStartTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择可领取开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="可领取结束时间" prop="receiveEndTime">
          <el-date-picker clearable
            v-model="form.receiveEndTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择可领取结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否固定使用时间, 默认0 否， 1是" prop="isFixedTime">
          <el-input v-model="form.isFixedTime" placeholder="请输入是否固定使用时间, 默认0 否， 1是" />
        </el-form-item>
        <el-form-item label="可使用时间范围 开始时间" prop="useStartTime">
          <el-date-picker clearable
            v-model="form.useStartTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择可使用时间范围 开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="可使用时间范围 结束时间" prop="useEndTime">
          <el-date-picker clearable
            v-model="form.useEndTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择可使用时间范围 结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="天数" prop="day">
          <el-input v-model="form.day" placeholder="请输入天数" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="StoreCoupon" lang="ts">
import { listStoreCoupon, getStoreCoupon, delStoreCoupon, addStoreCoupon, updateStoreCoupon } from '@/api/crm/storeCoupon';
import { StoreCouponVO, StoreCouponQuery, StoreCouponForm } from '@/api/crm/storeCoupon/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const storeCouponList = ref<StoreCouponVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const storeCouponFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: StoreCouponForm = {
  id: undefined,
  name: undefined,
  money: undefined,
  isLimited: undefined,
  total: undefined,
  lastTotal: undefined,
  useType: undefined,
  primaryKey: undefined,
  minPrice: undefined,
  receiveStartTime: undefined,
  receiveEndTime: undefined,
  isFixedTime: undefined,
  useStartTime: undefined,
  useEndTime: undefined,
  day: undefined,
  type: undefined,
  sort: undefined,
  status: undefined,
}
const data = reactive<PageData<StoreCouponForm, StoreCouponQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    money: undefined,
    isLimited: undefined,
    total: undefined,
    lastTotal: undefined,
    useType: undefined,
    primaryKey: undefined,
    minPrice: undefined,
    receiveStartTime: undefined,
    receiveEndTime: undefined,
    isFixedTime: undefined,
    useStartTime: undefined,
    useEndTime: undefined,
    day: undefined,
    type: undefined,
    sort: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "优惠券表ID不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "优惠券名称不能为空", trigger: "blur" }
    ],
    money: [
      { required: true, message: "兑换的优惠券面值不能为空", trigger: "blur" }
    ],
    isLimited: [
      { required: true, message: "是否限量, 默认0 不限量， 1限量不能为空", trigger: "blur" }
    ],
    total: [
      { required: true, message: "发放总数不能为空", trigger: "blur" }
    ],
    lastTotal: [
      { required: true, message: "剩余数量不能为空", trigger: "blur" }
    ],
    useType: [
      { required: true, message: "使用类型 1 全场通用, 2 商品券, 3 品类券不能为空", trigger: "change" }
    ],
    primaryKey: [
      { required: true, message: "所属商品id / 分类id不能为空", trigger: "blur" }
    ],
    minPrice: [
      { required: true, message: "最低消费，0代表不限制不能为空", trigger: "blur" }
    ],
    receiveStartTime: [
      { required: true, message: "可领取开始时间不能为空", trigger: "blur" }
    ],
    receiveEndTime: [
      { required: true, message: "可领取结束时间不能为空", trigger: "blur" }
    ],
    isFixedTime: [
      { required: true, message: "是否固定使用时间, 默认0 否， 1是不能为空", trigger: "blur" }
    ],
    useStartTime: [
      { required: true, message: "可使用时间范围 开始时间不能为空", trigger: "blur" }
    ],
    useEndTime: [
      { required: true, message: "可使用时间范围 结束时间不能为空", trigger: "blur" }
    ],
    day: [
      { required: true, message: "天数不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "优惠券类型 1 手动领取, 2 新人券, 3 赠送券不能为空", trigger: "change" }
    ],
    sort: [
      { required: true, message: "排序不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询优惠券列表 */
const getList = async () => {
  loading.value = true;
  const res = await listStoreCoupon(queryParams.value);
  storeCouponList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  storeCouponFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: StoreCouponVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加优惠券";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: StoreCouponVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getStoreCoupon(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改优惠券";
}

/** 提交按钮 */
const submitForm = () => {
  storeCouponFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateStoreCoupon(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addStoreCoupon(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: StoreCouponVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除优惠券编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delStoreCoupon(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('crm/storeCoupon/export', {
    ...queryParams.value
  }, `storeCoupon_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
